package com.learning.jquizenglish.screen.profile;

import java.io.File;
import java.util.ArrayList;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.learning.jquizenglish.R;
import com.learning.jquizenglish.activity.MainActivity;
import com.learning.jquizenglish.common.controller.JQuizHistory;
import com.learning.jquizenglish.common.fragment.JQuizEnglishFragment;
import com.learning.jquizenglish.model.ActivityResultData;
import com.learning.jquizenglish.model.HistoryModel;
import com.learning.jquizenglish.model.JQuizObserver;
import com.learning.jquizenglish.model.JQuizRequestModel;
import com.learning.jquizenglish.model.ProfileModel;
import com.learning.jquizenglish.model.ProfileUpdateModel;
import com.learning.jquizenglish.model.UserRowModel;
import com.learning.jquizenglish.network.JQuizEnglishApi;
import com.learning.jquizenglish.utility.CameraUtils;
import com.learning.jquizenglish.widget.smoothprogressbar.SmoothProgressBar;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

// TODO: Auto-generated Javadoc
/**
 * The Class ProfileScreen.
 */
public class ProfileScreen extends JQuizEnglishFragment implements JQuizObserver{

	/** The m list view. */
	private ListView mListView;
	
	/** The m smooth progress bar. */
	private SmoothProgressBar mSmoothProgressBar;
	
	/** The m profile model. */
	private ProfileModel mProfileModel;
	
	/** The m history model. */
	private HistoryModel mHistoryModel;
	
	/** The m list row. */
	private ArrayList<UserRowModel> mListRow; 
	
	private Uri imageUri;
	
	private ImageView imgAvatar;
	
	private String imagePath;
	/* (non-Javadoc)
	 * @see com.learning.jquizenglish.common.fragment.BaseFragment#onCreateContentView(android.view.LayoutInflater, android.view.ViewGroup)
	 */
	@Override
	protected View onCreateContentView(LayoutInflater inflater,
			ViewGroup container) {
		View v = inflater.inflate(R.layout.screen_profile, container, false);
		mListView = (ListView) v.findViewById(R.id.listview);
		mSmoothProgressBar = (SmoothProgressBar) v.findViewById(R.id.progressbar);
		requestUserData();
		((MainActivity)getActivity()).registerProfileListener(this);
		return v;
	}
	
	/**
	 * Inits the data.
	 */
	private void initData(){
		mListRow = new ArrayList<UserRowModel>();
		if (mProfileModel!=null){
			mListRow.addAll(mProfileModel.convertToListRowModel());
		}
		if (mHistoryModel!=null) {
			mListRow.addAll(mHistoryModel.convertToListRowModel());
		}
		ProfileAdapter adapter = new ProfileAdapter(this, mListRow);
		mListView.setAdapter(adapter);
		mSmoothProgressBar.setVisibility(View.INVISIBLE);
	}
	
	/**
	 * Request user data.
	 */
	public void requestUserData(){
//		mProfileModel = ProfilePreference.getInstance().getProfile();
//		if(mProfileModel != null){
//			requestHistoryData();
//			return;
//		}
		mSmoothProgressBar.setVisibility(View.VISIBLE);
		JQuizRequestModel requestModel = JQuizEnglishApi.getRequestProfile(getActivity());
		executePostTask(requestModel, false, ProfileModel.class, new JQuizTaskListener() {
			
			@Override
			public void onTaskComplete(Object object) {
				if (object!=null) {
					mProfileModel = (ProfileModel)object;
					ProfilePreference.getInstance().setProfile(mProfileModel);
					ProfilePreference.getInstance().saveChange();
				}
				requestHistoryData();
			}
		});
	}
	
	/**
	 * Update profile.
	 *
	 * @param model the model
	 */
	public void updateProfile(ProfileModel model){
		mSmoothProgressBar.setVisibility(View.VISIBLE);
		ProfileUpdateModel updateModel = new ProfileUpdateModel();
		updateModel.name = model.name == null ? "":model.name;
		updateModel.living_in = model.living_in == null ? "":model.living_in;
		updateModel.about_you = model.about_you == null ? "":model.about_you;
		updateModel.imei = model.imei == null ? "":model.imei;
		String jsonData = updateModel.convertToJsonString();
		JQuizRequestModel requestModel = JQuizEnglishApi.getRequestUpdateProfile(jsonData);
		executePostTaskReturnList(requestModel, false, ProfileModel.class, new JQuizTaskListener() {
			
			@Override
			public void onTaskComplete(Object object) {
				if (object!=null) {
					ArrayList<ProfileModel> listProfile = (ArrayList<ProfileModel>) object;
					if(listProfile!=null && listProfile.size()>0){
						ProfileModel profileReturn = listProfile.get(0);
						mProfileModel.name = profileReturn.name;
						mProfileModel.living_in = profileReturn.living_in;
						mProfileModel.about_you = profileReturn.about_you;
						mProfileModel.imei = profileReturn.imei;
						ProfilePreference.getInstance().setProfile(mProfileModel);
						refreshData();
					}
				}
				mSmoothProgressBar.setVisibility(View.INVISIBLE);
			}
		});
	}
	
	/**
	 * Request history data.
	 */
	public void requestHistoryData(){
//		mHistoryModel = JQuizHistory.getInstance().getHistoryModel();
//		if (mHistoryModel!=null) {
//			initData();
//			return;
//		}
		JQuizRequestModel requestModel = JQuizEnglishApi.getRequestListHistory(getActivity());
		executeGetTask(requestModel, false, HistoryModel.class, new JQuizTaskListener() {
			
			@Override
			public void onTaskComplete(Object object) {
				if (object!=null) {
					mHistoryModel = (HistoryModel) object;
					JQuizHistory.getInstance().setHistoryModel(mHistoryModel);
				}
				initData();
			}
		});
	}
	
	/**
	 * Refresh data.
	 */
	public void refreshData(){
		mListRow = new ArrayList<UserRowModel>();
		mProfileModel = ProfilePreference.getInstance().getProfile();
		mHistoryModel = JQuizHistory.getInstance().getHistoryModel();
		if (mProfileModel!=null){
			mListRow.addAll(mProfileModel.convertToListRowModel());
		}
		if (mHistoryModel!=null) {
			mListRow.addAll(mHistoryModel.convertToListRowModel());
		}
		ProfileAdapter adapter = new ProfileAdapter(this, mListRow);
		mListView.setAdapter(adapter);
	}
	
	public void startCameraForResult(){
		imagePath = CameraUtils.startCameraForResult(getActivity(), MainActivity.PICK_CAMERA_REQUEST_CODE);
		imageUri = Uri.fromFile(new File(imagePath));
	}
	
	public void startGaleryForResult(){
		imagePath = null;
		CameraUtils.startGalleryForResult(getActivity(), MainActivity.PICK_FROM_FILE_REQUEST_CODE);
	}
	
	public void onActivityResult(int requestCode,int resultCode,Intent data){
		switch (requestCode) {
		case MainActivity.PICK_CAMERA_REQUEST_CODE:
			changeAvatar();
			break;
		case MainActivity.PICK_FROM_FILE_REQUEST_CODE:
			imageUri = data.getData();
			changeAvatar();
			break;
		default:
			break;
		}
	}
	
	public void changeAvatar(){
		if(imageUri==null) return;
		ImageLoader.getInstance().displayImage(imageUri.toString(), imgAvatar,options);
		if (imagePath==null) {
//			imagePath = CameraUtils.getRealPathFromURI(getActivity(), imageUri);
			imagePath = CameraUtils.getPath(getActivity(), imageUri);
		}
		ProfilePreference.getInstance().saveAvatarUriToPref(imageUri.toString());
		JQuizRequestModel requestModel = JQuizEnglishApi.getRequestChangeAvatar(getActivity(), imagePath);
		executePostTaskReturnList(requestModel, false, ProfileModel.class, null);
//		executePostTaskReturnList(requestModel, false, ProfileModel.class, new JQuizTaskListener() {
//			
//			@Override
//			public void onTaskComplete(Object object) {
//				if (object!=null) {
//					ArrayList<ProfileModel> listProfile = (ArrayList<ProfileModel>) object;
//					ProfilePreference.getInstance().setProfile(listProfile.get(0));
//					mProfileModel = ProfilePreference.getInstance().getProfile();
////					ImageLoader.getInstance().displayImage(JQuizEnglishApi.BASE_IMAGE_URL+mProfileModel.avatar, imgAvatar,options);
//				}
//			}
//		});
	}
	
	public void showPopupGetImage(View avatar,UserRowModel model){
		imgAvatar = (ImageView) avatar;
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		View vContent = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_take_photo, null);
		TextView tvTakePhoto = (TextView) vContent.findViewById(R.id.tvTakePhoto);
		TextView tvChooseGallery = (TextView) vContent.findViewById(R.id.tvChooseGallery);
		tvTakePhoto.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				startCameraForResult();
			}
		});
		tvChooseGallery.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				startGaleryForResult();
			}
		});
		int dialogWidth = MainActivity.SCREEN_WIDTH*3/4;
		dialog.setContentView(vContent,new LayoutParams(dialogWidth, LayoutParams.WRAP_CONTENT));
		dialog.show();
	}
	

	/* (non-Javadoc)
	 * @see com.learning.jquizenglish.model.JQuizObserver#onUpdate(java.lang.Object)
	 */
	@Override
	public void onUpdate(Object ob) {
		if (ob instanceof ActivityResultData) {
			ActivityResultData model = ((ActivityResultData)ob);
			onActivityResult(model.requestCode, model.resultCode, model.intent);
		}else{
			requestUserData();
		}
	}
	
	public static DisplayImageOptions options = new DisplayImageOptions.Builder()
										.cacheInMemory(true)
										.cacheOnDisc(true)
										.bitmapConfig(Bitmap.Config.RGB_565)
										.considerExifParams(true)
										.showStubImage(R.drawable.baby)
										.showImageForEmptyUri(R.drawable.baby)
										.showImageOnFail(R.drawable.baby)
										.build();
}
